package com.tianyang.yukuaifu.base;

import android.app.Activity;
import android.database.ContentObserver;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.tianyang.yukuaifu.R;
import com.tianyang.yukuaifu.business.main.view.MainActivity;
import com.tianyang.yukuaifu.common.view.CommonTitleView;
import com.tianyang.yukuaifu.common.view.RippleLoadingDialog;
import com.tianyang.yukuaifu.jump.eventbus.OfflineEvent;
import com.tianyang.yukuaifu.module.immersionbar.ImmersionBar;
import com.tianyang.yukuaifu.module.immersionbar.OSUtils;
import com.tianyang.yukuaifu.rxservice.RxError;
import com.tianyang.yukuaifu.utils.AppContextUtil;
import com.tianyang.yukuaifu.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.Calendar;

import butterknife.ButterKnife;

/**
 * Description：具有自定义Header的基础类
 */
public abstract class BaseTitleActivity extends BaseActivity {

    private RippleLoadingDialog loadingDialog;

    protected Bundle savedInstanceState;

    protected CommonTitleView commonTitle;

    protected ImmersionBar mImmersionBar;

    private String NAVIGATIONBAR_IS_MIN = "navigationbar_is_min";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setBackgroundDrawable(null);
        setContentView(R.layout.base_view_header);
        this.savedInstanceState = savedInstanceState;
        View contentView = LayoutInflater.from(mContext).inflate(getLayoutResID(), null);
        ((LinearLayout)findViewById(R.id.baseHeader)).addView(contentView, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        ButterKnife.bind(this);
        //初始化沉浸式
        if (isImmersionBarEnabled()) {
            initImmersionBar();
        }
        initView();
        setListener();
        initData();
        if (hasBindEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissLoadingDialog();
        if (hasBindEventBus()) {
            EventBus.getDefault().unregister(this);
        }
        if (mImmersionBar != null)
            mImmersionBar.destroy();  //在BaseActivity里销毁
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        //解决华为emui3.0与3.1手机手动隐藏底部导航栏时，导航栏背景色未被隐藏的问题
        if (OSUtils.isEMUI3_1()) {
            //第一种
            getContentResolver().registerContentObserver(Settings.System.getUriFor
                    (NAVIGATIONBAR_IS_MIN), true, mNavigationStatusObserver);
            //第二种,禁止对导航栏的设置
            //mImmersionBar.navigationBarEnable(false).init();
        }
        mImmersionBar.statusBarColorTransformEnable(true)
                .statusBarView(R.id.topView)
                .statusBarDarkFont(true, 0.5f)
                .statusBarColor(R.color.white)
                .fullScreen(false)
                .init();
    }

    private ContentObserver mNavigationStatusObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            try {
                int navigationBarIsMin = Settings.System.getInt(getContentResolver(),
                        NAVIGATIONBAR_IS_MIN, 0);
                mImmersionBar = ImmersionBar.with((Activity) mContext);
                if (navigationBarIsMin == 1) {
                    //导航键隐藏了
                    mImmersionBar.transparentNavigationBar().init();
                } else {
                    //导航键显示了
                    mImmersionBar.navigationBarColor(R.color.c_2b2e33) //隐藏前导航栏的颜色
                            .fullScreen(false)
                            .init();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
    }

    protected String getTag() {
        return getClass().getSimpleName();
    }

    protected abstract int getLayoutResID();

    protected void initView() {
        commonTitle = (CommonTitleView) findViewById(R.id.commonTitle);
        if (hasCommonTitle()) {
            commonTitle.setVisibility(View.VISIBLE);
            commonTitle.setLeftOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        } else {
            commonTitle.setVisibility(View.GONE);
        }
    }

    protected void initData() {
    }

    protected void setListener() {
    }

    /**
     * 当前页面是否有EventBus。 默认为false
     *
     * @return
     */
    protected abstract boolean hasBindEventBus();

    /**
     * 是否有标题栏
     * @return
     */
    protected boolean hasCommonTitle() {
        return true;
    }

    /**
     * 显示加载数据进度条
     */
    public void showLoadingDialog(boolean cancelable) {
        showLoadingDialog(cancelable, "正在加载中...");
    }

    /**
     * 显示加载数据进度条
     */
    public void showLoadingDialog(boolean cancelable, String content) {
        if (loadingDialog == null) {
            loadingDialog = new RippleLoadingDialog(this);
        } else {
            if (loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
        }
        loadingDialog.setInterceptDismiss(cancelable);
        if (!TextUtils.isEmpty(content));
            loadingDialog.title(content);
        loadingDialog.show();
    }

    /**
     * 取消正在显示的dialog
     */
    public void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

    private long lastClickTime = 0;

    public static final int MIN_CLICK_DELAY_TIME = 500;

    /**
     * 是否响应点击事件
     */
    public boolean isRespondEvent() {
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
            lastClickTime = currentTime;
            return true;
        }
        return false;
    }

    /**
     * 接口回调error提示错误信息
     * @param e
     */
    public void showErrorText(Throwable e) {
        if (e instanceof RxError) {
            RxError error = (RxError) e;
            if (TextUtils.equals(RxError.ERROR_OFFLINE, error.errorCode)) {
                AppContextUtil.finishAllExclByActivity(MainActivity.class.getName());
                EventBus.getDefault().post(new OfflineEvent("你的账号已在另外一台设备登录，请重新登录!"));
            } else if (TextUtils.equals(RxError.ERROR_UNKNOWN, error.errorCode)) {
                ToastUtil.showTextViewPrompt("网络异常!");
            } else if (!TextUtils.isEmpty(error.getMessage()))  {
                ToastUtil.showTextViewPrompt(error.getMessage());
            }
        } else if (e instanceof SocketTimeoutException) {
            ToastUtil.showTextViewPrompt("网络连接超时!");
        } else if (e instanceof ConnectException) {
            ToastUtil.showTextViewPrompt("网络连接异常!");
        } else {
            ToastUtil.showTextViewPrompt("系统服务故障!");
        }
    }
}
